<template>
  <div class="koi-flex">
    <KoiSearch :isFold="true" :showSearch="showSearch">
      <!-- 搜索条件 -->
      <el-form :inline="true">
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            placeholder="请输入角色名称"
            v-model="searchParams.roleName"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleListPage"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色编号" prop="roleCode">
          <el-input
            placeholder="请输入角色编号"
            v-model="searchParams.roleCode"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleListPage"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色状态" prop="roleStatus">
          <el-select
            placeholder="请选择角色状态"
            v-model="searchParams.roleStatus"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleListPage"
          >
            <el-option label="启用" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain @click="handleSearch()" v-auth="['system:role:search']">{{
            $t("button.search")
          }}</el-button>
          <el-button type="danger" icon="refresh" plain @click="resetSearch()">{{ $t("button.reset") }}</el-button>
        </el-form-item>
      </el-form>
    </KoiSearch>
    <KoiCard>
      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5" v-auth="['system:role:add']">
          <el-button type="primary" icon="plus" plain @click="handleAdd()">{{ $t("button.add") }}</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['system:role:update']">
          <el-button type="success" icon="edit" plain @click="handleUpdate()" :disabled="single">{{
            $t("button.update")
          }}</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['system:role:delete']">
          <el-button type="danger" icon="delete" plain @click="handleBatchDelete()" :disabled="multiple">{{
            $t("button.delete")
          }}</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['system:role:menu']">
          <el-button type="success" icon="Postcard" plain :disabled="single" @click="handleAssignMenu()">{{
            $t("button.menu")
          }}</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['system:role:dept']">
          <el-button type="primary" icon="FolderOpened" plain :disabled="single" @click="handleAssignDept()">{{
            $t("button.dept")
          }}</el-button>
        </el-col>
        <KoiToolbar v-model:showSearch="showSearch" @refreshTable="handleListPage"></KoiToolbar>
      </el-row>

      <div class="h-20px"></div>
      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        border
        :data="tableList"
        :empty-text="$t('msg.null')"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" prop="roleId" width="120px" align="center" type="index"></el-table-column>
        <el-table-column
          label="角色名称"
          prop="roleName"
          width="150px"
          :show-overflow-tooltip="true"
          align="center"
        ></el-table-column>
        <el-table-column label="角色编号" prop="roleCode" width="260px" align="center"></el-table-column>
        <!-- 注意：如果后端数据返回的是字符串"0" OR "1"，这里的active-value AND inactive-value不需要加冒号，会认为是字符串，否则：后端返回是0 AND 1数字，则需要添加冒号 -->
        <el-table-column label="角色状态" prop="roleStatus" width="100px" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.roleStatus"
              :active-text="$t('dict.sys_switch_status.open')"
              :inactive-text="$t('dict.sys_switch_status.stop')"
              active-value="0"
              inactive-value="1"
              :inline-prompt="true"
              @change="handleSwitch(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="数据范围" prop="dataScope" width="200px" align="center">
          <template #default="scope">
            <el-tag :type="dataScopeMap[scope.row.dataScope]?.type || 'info'">
              {{ dataScopeMap[scope.row.dataScope]?.label || "未知状态" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="角色排序" prop="sorted" width="100px" align="center"></el-table-column>
        <el-table-column
          label="角色备注"
          prop="remark"
          width="260px"
          :show-overflow-tooltip="true"
          align="center"
        ></el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="180px" align="center"></el-table-column>
        <el-table-column
          :label="$t('table.operate')"
          align="center"
          width="200"
          fixed="right"
          v-auth="['system:role:update', 'system:role:delete', 'system:role:menu', 'system:role:dept']"
        >
          <template #default="{ row }">
            <el-tooltip :content="$t('button.update')" placement="top">
              <el-button
                type="primary"
                icon="Edit"
                circle
                plain
                @click="handleUpdate(row)"
                v-auth="['system:role:update']"
              ></el-button>
            </el-tooltip>
            <el-tooltip :content="$t('button.delete')" placement="top">
              <el-button
                type="danger"
                icon="Delete"
                circle
                plain
                @click="handleDelete(row)"
                v-auth="['system:role:delete']"
              ></el-button>
            </el-tooltip>
            <el-tooltip :content="$t('button.menu')" placement="top" v-if="row.roleId != 1">
              <el-button
                type="info"
                icon="Postcard"
                circle
                plain
                @click="handleAssignMenu(row)"
                v-auth="['system:role:menu']"
              ></el-button>
            </el-tooltip>
            <el-tooltip :content="$t('button.dept')" placement="top" v-if="row.roleId != 1">
              <el-button
                type="success"
                icon="FolderOpened"
                circle
                plain
                @click="handleAssignDept(row)"
                v-auth="['system:role:dept']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <div class="h-20px"></div>
      <!-- 分页 -->
      <el-pagination
        background
        v-model:current-page="searchParams.pageNo"
        v-model:page-size="searchParams.pageSize"
        v-show="total > 0"
        :page-sizes="[10, 20, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleListPage"
        @current-change="handleListPage"
      />

      <!-- 添加 OR 修改 -->
      <KoiDialog
        ref="koiDialogRef"
        :title="title"
        @koiConfirm="handleConfirm"
        @koiCancel="handleCancel"
        :loading="confirmLoading"
      >
        <template #content>
          <el-form ref="formRef" :rules="rules" :model="form" label-width="auto" status-icon>
            <el-row :gutter="10">
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }">
                <el-form-item label="角色名称" prop="roleName">
                  <el-input v-model="form.roleName" placeholder="请输入角色名称" maxlength="32" show-word-limit clearable />
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }">
                <el-form-item label="角色编号" prop="roleCode">
                  <el-input v-model="form.roleCode" placeholder="请输入角色编号" maxlength="32" show-word-limit clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="10">
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }">
                <el-form-item label="角色状态" prop="roleStatus">
                  <el-select v-model="form.roleStatus" placeholder="请选择角色状态" clearable>
                    <el-option :label="$t('dict.sys_switch_status.open')" value="0" />
                    <el-option :label="$t('dict.sys_switch_status.stop')" value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }">
                <el-form-item label="角色排序" prop="sorted">
                  <el-input-number v-model="form.sorted" clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="角色备注" prop="remark">
                  <el-input
                    v-model="form.remark"
                    :rows="5"
                    type="textarea"
                    placeholder="请输入角色备注"
                    maxlength="64"
                    show-word-limit
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </KoiDialog>

      <!-- 分配菜单 -->
      <!-- check-strictly 为 false 父子联动，为 true 父子不联动  -->
      <KoiDrawer
        ref="koiMenuDrawerRef"
        :title="title"
        size="360"
        @koiConfirm="handleMenuConfirm"
        @koiCancel="handleMenuCancel"
        :loading="confirmLoading"
        cancelText="关闭"
      >
        <template #content>
          <div>
            <el-tree
              ref="menuTreeRef"
              :data="menuTreeData"
              show-checkbox
              :default-expand-all="false"
              :default-expanded-keys="expandedKey"
              node-key="menuId"
              :check-strictly="false"
              highlight-current
              :props="defaultMenuProps"
            >
              <template #default="{ node }">
                {{ $t(String(node.label)) || node.label }}
              </template>
            </el-tree>
          </div>
        </template>
      </KoiDrawer>

      <!-- 分配部门权限数据 -->
      <!-- check-strictly 为 false 父子联动，为 true 父子不联动  -->
      <KoiDrawer
        ref="koiDeptDrawerRef"
        :title="title"
        size="360"
        @koiConfirm="handleDeptConfirm"
        @koiCancel="handleDeptCancel"
        :loading="confirmLoading"
        cancelText="关闭"
      >
        <template #content>
          <el-form ref="formDeptRef" :rules="deptRules" :model="formDept" label-width="auto" label-position="top" status-icon>
            <el-row>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="角色名称" prop="roleName">
                  <el-input v-model="formDept.roleName" placeholder="请输入角色名称" maxlength="32" show-word-limit disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="角色编号" prop="roleCode">
                  <el-input v-model="formDept.roleCode" placeholder="请输入角色编号" maxlength="32" show-word-limit disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="权限范围" prop="dataScope">
                  <el-select placeholder="请选择权限范围" v-model="formDept.dataScope" @change="changeDataScope">
                    <el-option label="自定义数据权限" value="2" />
                    <el-option label="全部数据权限" value="1" v-auth="['*']" />
                    <el-option label="本部门及以下数据权限" value="3" />
                    <el-option label="本部门数据权限" value="5" />
                    <el-option label="仅本人数据权限" value="6" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="formDept.dataScope === '2'">
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="数据权限">
                  <el-tree
                    class="flex-1"
                    ref="deptTreeRef"
                    :data="deptTreeData"
                    show-checkbox
                    :default-expand-all="false"
                    :default-expanded-keys="expandedKey"
                    node-key="deptId"
                    :check-strictly="true"
                    highlight-current
                    :props="defaultDeptProps"
                  >
                  </el-tree>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </KoiDrawer>
    </KoiCard>
  </div>
</template>

<script setup lang="ts" name="rolePage">
import { nextTick, ref, reactive, onMounted } from "vue";
import { koiMsgSuccess, koiMsgWarning, koiMsgError } from "@/utils/koi.ts";
import { ElMessageBox } from "element-plus";
import { listPage, getById, add, update, deleteById, batchDelete, updateStatus, getSorted } from "@/api/system/role/index.ts";
import { listMenuNormal, listMenuIdsByRoleId, saveRoleMenu } from "@/api/system/menu/index.ts";
import { listDeptNormal, listDeptIdsByRoleId, saveRoleDept } from "@/api/system/dept/index.ts";
import { handleTree } from "@/utils/index.ts";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
// 表格加载动画Loading
const loading = ref(false);
// 是否显示搜索表单[默认显示]
const showSearch = ref<boolean>(true);
// 表格数据
const tableList = ref<any>([]);

// 查询参数
const searchParams = ref<any>({
  pageNo: 1, // 第几页
  pageSize: 10, // 每页显示多少条
  roleName: undefined,
  roleCode: undefined,
  roleStatus: undefined
});

const total = ref<number>(0);

/** 重置搜索参数 */
const resetSearchParams = () => {
  searchParams.value = {
    pageNo: 1,
    pageSize: 10,
    roleName: undefined,
    roleCode: undefined,
    roleStatus: undefined
  };
};

/** 搜索 */
const handleSearch = () => {
  searchParams.value.pageNo = 1;
  handleListPage();
};

/** 重置 */
const resetSearch = () => {
  resetSearchParams();
  handleListPage();
};

/** @current-change：点击分页组件页码发生变化：例如：切换第2、3页 OR 上一页 AND 下一页 OR 跳转某一页 */
/** @size-change：点击分页组件下拉选择条数发生变化：例如：选择10条/页、20条/页等 */
// 分页查询，@current-change AND @size-change都会触发分页，调用后端分页接口
/** 数据表格 */
const handleListPage = async () => {
  try {
    loading.value = true;
    tableList.value = []; // 重置表格数据
    const res: any = await listPage(searchParams.value);
    tableList.value = res.data.records;
    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

/** 数据表格[删除、批量删除等刷新使用] */
const handleTableData = async () => {
  try {
    const res: any = await listPage(searchParams.value);
    tableList.value = res.data.records;
    total.value = res.data.total;
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

// 定义状态映射表[集中管理]
const dataScopeMap: any = {
  "1": { label: "全部数据权限", type: "success" },
  "2": { label: "自定义数据权限", type: "warning" },
  "3": { label: "本部门及以下数据权限", type: "primary" },
  "5": { label: "本部门数据权限", type: "primary" },
  "6": { label: "仅本人数据权限", type: "info" }
};

onMounted(() => {
  // 获取表格数据
  handleListPage();
});

const ids = ref([]); // 选择数组
const single = ref<boolean>(true); // 非单个禁用
const multiple = ref<boolean>(true); // 非多个禁用

/** 是否多选 */
const handleSelectionChange = (selection: any) => {
  console.log(selection);
  ids.value = selection.map((item: any) => item.roleId);
  single.value = selection.length != 1; // 单选
  multiple.value = !selection.length; // 多选
};

/** 获取最新排序数字 */
const handleSorted = async () => {
  try {
    const res: any = await getSorted();
    form.value.sorted = res.data;
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

/** 添加 */
const handleAdd = () => {
  // 打开对话框
  koiDialogRef.value.koiOpen();
  // 重置表单
  resetForm();
  // 标题
  title.value = t("button.add");
  form.value.roleStatus = "0";
  form.value.dataScope = "3";
  handleSorted();
};

/** 回显数据 */
const handleEcho = async (id: any) => {
  if (id == null || id == "") {
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  try {
    const res: any = await getById(id);
    form.value = res.data;
  } catch (error) {
    koiMsgError(t("msg.fail"));
    console.log(error);
  }
};

/** 修改 */
const handleUpdate = async (row?: any) => {
  // 打开对话框
  koiDialogRef.value.koiOpen();
  // 重置表单
  resetForm();
  // 标题
  title.value = t("button.update");
  const roleId = row ? row.roleId : ids.value[0];
  // 回显数据
  handleEcho(roleId);
};

// 添加 OR 修改对话框Ref
const koiDialogRef = ref();
// 标题
const title = ref();
// form表单Ref
const formRef = ref<any>();
// form表单
let form = ref<any>({
  roleId: undefined,
  roleName: undefined,
  roleCode: undefined,
  roleStatus: "0",
  dataScope: undefined,
  sorted: 1,
  remark: undefined
});

/** 清空表单数据 */
const resetForm = () => {
  // 等待 DOM 更新完成
  nextTick(() => {
    if (formRef.value) {
      // 重置该表单项，将其值重置为初始值，并移除校验结果
      formRef.value.resetFields();
    }
  });
  form.value = {
    roleId: undefined,
    roleName: undefined,
    roleCode: undefined,
    roleStatus: "0",
    dataScope: undefined,
    sorted: 1,
    remark: undefined
  };
};

/** 表单规则 */
const rules = reactive({
  roleName: [{ required: true, message: "请输入角色名字", trigger: "blur" }],
  roleCode: [{ required: true, message: "请输入角色编号", trigger: "blur" }],
  roleStatus: [{ required: true, message: "请输入选择角色状态", trigger: "blur" }],
  sorted: [{ required: true, message: "请输入排序号", trigger: "blur" }]
});

// 确定按钮是否显示Loading
const confirmLoading = ref(false);

/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      if (form.value.roleId != null && form.value.roleId != "") {
        try {
          await update(form.value);
          koiMsgSuccess(t("msg.success"));
          confirmLoading.value = false;
          koiDialogRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiMsgError(t("msg.fail"));
        }
      } else {
        try {
          await add(form.value);
          koiMsgSuccess(t("msg.success"));
          confirmLoading.value = false;
          koiDialogRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiMsgError(t("msg.fail"));
        }
      }
    } else {
      koiMsgError(t("msg.validFail"));
      confirmLoading.value = false;
    }
  });
};

/** 取消 */
const handleCancel = () => {
  koiDialogRef.value.koiClose();
};

/** 状态开关 */
const handleSwitch = (row: any) => {
  let text = row.roleStatus === "0" ? t("dict.sys_switch_status.open") : t("dict.sys_switch_status.stop");
  if (!row.roleId || !row.roleStatus) {
    row.roleStatus = row.roleStatus == "0" ? "1" : "0";
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  ElMessageBox.confirm(t("msg.confirmWant") + "[" + text + "]-[" + row.roleName + "]?", t("msg.remind"), {
    confirmButtonText: t("button.confirm"),
    cancelButtonText: t("button.cancel"),
    type: "warning"
  })
    .then(async () => {
      try {
        await updateStatus(row.roleId, row.roleStatus);
        koiMsgSuccess(t("msg.success"));
      } catch (error) {
        console.log(error);
        row.roleStatus = row.roleStatus == "0" ? "1" : "0";
        handleTableData();
        koiMsgError(t("msg.fail"));
      }
    })
    .catch(() => {
      row.roleStatus = row.roleStatus == "0" ? "1" : "0";
      koiMsgWarning(t("msg.cancelled"));
    });
};

/** 删除 */
const handleDelete = (row: any) => {
  const id = row.roleId;
  if (id == null || id == "") {
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  ElMessageBox.confirm(t("msg.confirmDelete"), t("msg.remind"), {
    confirmButtonText: t("button.confirm"),
    cancelButtonText: t("button.cancel"),
    type: "warning"
  })
    .then(async () => {
      try {
        await deleteById(id);
        handleTableData();
        koiMsgSuccess(t("msg.success"));
      } catch (error) {
        console.log(error);
        handleTableData();
        koiMsgError(t("msg.fail"));
      }
    })
    .catch(() => {
      koiMsgWarning(t("msg.cancelled"));
    });
};

/** 批量删除 */
const handleBatchDelete = () => {
  if (ids.value.length == 0) {
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  ElMessageBox.confirm(t("msg.confirmDelete"), t("msg.remind"), {
    confirmButtonText: t("button.confirm"),
    cancelButtonText: t("button.cancel"),
    type: "warning"
  })
    .then(async () => {
      try {
        await batchDelete(ids.value);
        handleTableData();
        koiMsgSuccess(t("msg.success"));
      } catch (error) {
        console.log(error);
        handleTableData();
        koiMsgError(t("msg.fail"));
      }
    })
    .catch(() => {
      koiMsgWarning(t("msg.cancelled"));
    });
};

/** 分配菜单 Begin */

const koiMenuDrawerRef = ref();
const menuTreeRef = ref();
const menuTreeData = ref<any>([]); // 菜单树数据
const deptTreeData = ref<any>([]); // 部门树数据

// 配置属性
const defaultMenuProps = {
  id: "menuId",
  label: "menuName",
  children: "children"
};

// 默认展开配置
const expandedKey = ref();
const roleId = ref();

/** 分配菜单 */
const handleAssignMenu = async (row?: any) => {
  title.value = t("button.menu");
  // 置空
  menuTreeRef.value?.setCheckedKeys([], false);
  expandedKey.value = [];
  menuTreeData.value = [];
  roleId.value = row?.roleId || ids.value[0];
  if (roleId.value == null || roleId.value == "") {
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  // 查询所有的菜单权限
  koiMenuDrawerRef.value.koiOpen();
  // console.log("角色ID",ids.value[0]);
  // 查询所有的菜单权限
  try {
    const res: any = await listMenuNormal();
    menuTreeData.value = handleTree(res.data.menuList, "menuId");
    expandedKey.value = res.data.spreadList;
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }

  // 通过key设置反选角色拥有的菜单权限(只能查询子节点，查询父节点将直接选择全部下的子节点)
  try {
    const res: any = await listMenuIdsByRoleId(roleId.value);
    // console.log('res',res.data)
    // menuTreeRef.value?.setCheckedKeys([1,2,3], false);
    if (res.data) {
      menuTreeRef.value?.setCheckedKeys(res.data, false);
    }
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

/** 保存菜单权限 */
const handleMenuConfirm = async () => {
  confirmLoading.value = true;
  // 获取选择的keys
  const checkedKeys = menuTreeRef.value?.getCheckedKeys(false);
  // console.log("选择",checkedKeys)
  // 获取半选的keys(即保存选择子节点的父节点[父节点下的子节点并没有选择完])
  const halfCheckKeys = menuTreeRef.value?.getHalfCheckedKeys();
  // console.log("半选",halfCheckKeys)
  // 组合成最后的keys
  const finalKey = halfCheckKeys.concat(checkedKeys);
  // console.log("最终",finalKey)

  try {
    await saveRoleMenu(roleId.value, finalKey);
    confirmLoading.value = false;
    koiMenuDrawerRef.value.koiQuickClose();
    koiMsgSuccess(t("msg.success"));
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

/** 取消 */
const handleMenuCancel = () => {
  koiMenuDrawerRef.value.koiClose();
};

/** 分配菜单 End */

/** 分配部门权限数据 Begin */

const koiDeptDrawerRef = ref();
const deptTreeRef = ref();

// 配置属性
const defaultDeptProps = {
  id: "deptId",
  label: "deptName",
  children: "children"
};

const formDeptRef = ref();
const formDept = ref<any>({
  roleId: undefined,
  roleName: undefined,
  roleCode: undefined,
  roleStatus: undefined,
  sorted: undefined,
  dataScope: undefined
});

/** 表单规则 */
const deptRules = reactive({
  dataScope: [{ required: true, message: "请选择权限范围", trigger: "blur" }]
});

/** 分配部门 */
const handleAssignDept = (row?: any) => {
  // console.log(row.roleId);
  title.value = t("button.dept");
  // 置空
  deptTreeRef.value?.setCheckedKeys([], false);
  expandedKey.value = [];
  deptTreeData.value = [];
  roleId.value = row?.roleId || ids.value[0];
  if (roleId.value == null || roleId.value == "") {
    koiMsgWarning(t("msg.selectData"));
    return;
  }

  formDept.value.roleId = row?.roleId;
  formDept.value.roleName = row?.roleName;
  formDept.value.roleCode = row?.roleCode;
  formDept.value.roleStatus = row?.roleStatus;
  formDept.value.dataScope = row?.dataScope;
  formDept.value.sorted = row?.sorted;
  
  koiDeptDrawerRef.value.koiOpen();

  // console.log("角色ID",ids.value[0]);
  if (formDept.value.dataScope == "2") {
    handleDeptTree();
  }
};

/** 下拉框 change 时间 */
const changeDataScope = () => {
  if (formDept.value.dataScope == "2") {
    handleDeptTree();
  }
};

/** 查询部门树 和 回显数据 */
const handleDeptTree = async () => {
  // 查询该角色的部门权限
  try {
    const res: any = await listDeptNormal();
    deptTreeData.value = handleTree(res.data.deptList, "deptId");
    expandedKey.value = res.data.spreadList;
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
  // deptTreeRef.value?.setCheckedKeys(['3'], false);
  // 通过key设置反选角色拥有的菜单权限[只能查询子节点，查询父节点将直接选择全部下的子节点]
  try {
    const res: any = await listDeptIdsByRoleId(roleId.value);
    // console.log('res',res.data)
    if (res.data) {
      deptTreeRef.value?.setCheckedKeys(res.data, false);
    }
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

/** 保存部门权限 */
const handleDeptConfirm = async () => {
  if (!formDeptRef.value) return;
  (formDeptRef.value as any).validate(async (valid: any) => {
    if (valid) {
      confirmLoading.value = true;
      if (formDept.value.dataScope == "2") {
        // 获取选择的keys
        const checkedKeys = deptTreeRef.value?.getCheckedKeys(false);
        // console.log("选择",checkedKeys)
        // 获取半选的keys(即保存选择子节点的父节点[父节点下的子节点并没有选择完])
        const halfCheckKeys = deptTreeRef.value?.getHalfCheckedKeys();
        // console.log("半选",halfCheckKeys)
        // 组合成最后的keys
        const finalKey = halfCheckKeys.concat(checkedKeys);
        // console.log("最终",finalKey)

        try {
          await saveRoleDept(roleId.value, finalKey);
          confirmLoading.value = false;
          koiDeptDrawerRef.value.koiQuickClose();
          koiMsgSuccess(t("msg.success"));
        } catch (error) {
          console.log(error);
          koiMsgError(t("msg.fail"));
        }
      } else {
        if (formDept.value.roleId != null && form.value.roleId != "") {
          try {
            await update(formDept.value);
            koiMsgSuccess(t("msg.success"));
            confirmLoading.value = false;
            koiDeptDrawerRef.value.koiQuickClose();
            resetForm();
            handleListPage();
          } catch (error) {
            console.log(error);
            confirmLoading.value = false;
            koiMsgError(t("msg.fail"));
          }
        }
      }
    } else {
      koiMsgError(t("msg.validFail"));
      confirmLoading.value = false;
    }
  });
};

/** 取消 */
const handleDeptCancel = () => {
  koiDeptDrawerRef.value.koiClose();
};

/** 分配部门权限数据 End */
</script>

<style lang="scss" scoped></style>
